package com.heima.kafka.stream;

import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.TimeWindows;
import org.apache.kafka.streams.kstream.ValueMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;
import java.util.Arrays;
import java.util.List;

/**
 * @ClassName KafkaStreamHelloListener
 * @Description TODO
 * @Author kiku
 * @Date 2024/9/2 16:45
 * @Version 1.0
 */
@Configuration
@Slf4j
public class KafkaStreamHelloListener {

    @Bean
    public KStream<String, String> kStream(StreamsBuilder streamsBuilder) {
        //创建kstream对象并且指定从哪个topic接收消息
        KStream<String, String> kStream = streamsBuilder.stream("itcast-topic-input");
        kStream.flatMapValues(new ValueMapper<String, Iterable<String>>() {
                    @Override
                    public Iterable<String> apply(String value) {
                        String[] split = value.split(" ");
                        List<String> list = Arrays.asList(split);
                        return list;
                    }
                }).groupBy((key, value) -> value).windowedBy(TimeWindows.of(Duration.ofSeconds(10)))
                //统计单词的个数
                .count().toStream()
                .map((key, value) -> {
                    System.out.println("key" + key + ",value" + value);
                    return new KeyValue<>(key.key().toString(), value.toString());

                }).to("itcast-topic-out");
        return kStream;
    }
}
